module("Corps", package.seeall)

BaseCorps = class("BaseCorps")

BaseCorps.__index = BaseCorps

function create(isleft, scene)
	local ret = BaseCorps.new()
	ret.heros = {}
	ret.isleft = isleft
	ret.battlescene = scene
	return ret
end

function BaseCorps:addHero(hero)
	table.insert(self.heros, hero)
end

function BaseCorps:removeHero(her)
end

function BaseCorps:startBattle(battleScene, enemy)
	self.battleScene = battleScene
	self.enemyCorps = enemy
	for k,hero in ipairs(self.heros) do
		hero.enemyCorps = enemy
		if (self.isleft) then
			hero:turnTo("left")
		else
			hero:turnTo("right")
		end
		if (hero:getParent() == nil) then
			battleScene:addChild(hero)
		end
	end

	self:formation()
end

function BaseCorps:clear()
	for k,v in ipairs(self.heros) do
		v:removeFromParent()
	end

	self.heros = {}
end

function BaseCorps:formation()
	local winSize = cc.Director:getInstance():getWinSize()
	local halfHeight = winSize.height / 2
	local verticalVariation = winSize.height * 0.08
	local horizontalVariation = winSize.width * 0.2

	for k,hero in ipairs(self.heros) do
		local xOffset = horizontalVariation * math.random(-500, 500) / 500
		local yOffset = verticalVariation * math.random(-500, 500) / 500

		print(horizontalVariation, xOffset)
		print(verticalVariation, yOffset)

		if (self.isleft) then
			hero:setPosition(cc.p(xOffset - horizontalVariation * (k-1), yOffset + halfHeight - verticalVariation))
		else
			hero:setPosition(cc.p(xOffset + winSize.width + horizontalVariation * (k-1), yOffset + halfHeight - verticalVariation))
		end
	end
end

function BaseCorps:fillAllAliveHeros(container)
    for k, hero in ipairs(self.heros) do
        repeat
            if (not hero:isAlive()) then break end
            table.insert(container, k, hero)
        until true
    end
end

function BaseCorps:getNearestHero(target)
	if (#self.heros == 0) then
		return
	end

	local dis = cc.Director:getInstance():getWinSize().width * 2
	local nearestHero = nil

	for k=#self.heros,1,-1 do
		if (self.heros[k]:isAlive()) then
			local tDis = cc.pGetDistance(cc.p(target:getPosition()), cc.p(self.heros[k]:getPosition()))

			if (tDis < dis) then
				nearestHero = self.heros[k]
				dis = tDis
			end
		end
	end

	return nearestHero
end

function BaseCorps:hideAll()
	for k, hero in ipairs(self.heros) do
		hero:setVisible(false)
	end
end

function BaseCorps:isFailed( )
	for k,v in ipairs(self.heros) do
		if (v:isAlive()) then
			return true
		end
	end

	return false
end

function BaseCorps:onHeroDie( hero )
	for k,v in ipairs(self.heros) do
		if (v:isAlive()) then
			return
		end
	end

	self.enemyCorps:onWin()
	BattleScene.onBattleEnd(self.battlescene)
end

function BaseCorps:onWin()
	for k,v in ipairs(self.heros) do
		if (v:isAlive()) then
			v:unscheduleUpdate()
			v:onVictory()
		end
	end
end